<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CountingSort</title>
</head>

<body>
    <script>
        function countingSort(arr, maxValue) {
            let sortedIndex = 0
            //开一个大小为待排序数组最大值的新数组
            let bucket = new Array(maxValue + 1)
            //初始化bucket
            for (let a = 0; a < bucket.length; a++) {
                bucket[a] = 0
            }
            for (let i = 0; i < arr.length; i++) {
                bucket[arr[i]]++
            }
            for (let j = 0; j < bucket.length; j++) {
                while (bucket[j] > 0) {
                    arr[sortedIndex++] = j
                    bucket[j]--
                }
            }
            return arr
        }
        console.log(countingSort([9, 55, 4, 8, 1, 2], 55))
        let arr = [9, 55, 4, 8, 1, 2]
        let maxValue = Math.max(...arr)
        console.log(countingSort(arr, maxValue))
    </script>
</body>

</html>